import { _decorator, Component, Input, Node, Sprite, SpriteAtlas, UI, UITransform } from 'cc';
import { GAME_BOARD_ENUM, GAME_EVENT_ENUM } from './Enum';
import { CHANGE_BOARD } from './Event';
import { BlockType } from './type';
const { ccclass, property } = _decorator;

@ccclass('Block')
export class Block extends Component {
    id: number;
    //坐标
    x: number;
    y: number;
    //尺寸
    width: number;
    height: number;
    level: number;
    private _boardType: GAME_BOARD_ENUM;
    type: number;
    higherIds: number[];
    lowerIds: number[];
    //初始化原始数据
    old_boardType: GAME_BOARD_ENUM;
    old_x: number;
    old_y: number;
    old_width: number;
    old_height: number;
    old_level: number;

    @property(SpriteAtlas)
    spriteAtlas: SpriteAtlas = null;

    get boardType(): string {
        return this._boardType;
    }

    set boardType(data: GAME_BOARD_ENUM) {
        if (this._boardType != data) {
            this._boardType = data;
        }
        //CHANGE_BOARD.emit(GAME_EVENT_ENUM.CHANGE_BOARD, this);
    }

    //初始化
    init(block: BlockType) {
        //将block的属性和平到当前的对象中
        Object.assign(this, block);

        //存储旧的类型数据
        this.old_boardType = block.boardType;
        this.old_x = block.x;
        this.old_y = block.y;
        this.old_width = block.width;
        this.old_height = block.height;
        this.old_level = block.level;
        //渲染当前对象
        this.render();
    }

    //块渲染更新
    render() {
        this.node.setPosition(this.x, this.y);
        this.node.getComponent(UITransform).width = this.width;
        this.node.getComponent(UITransform).height = this.height;
        this.node.getComponent(UITransform).priority = this.level;
        this.node.getComponent(Sprite).spriteFrame = this.spriteAtlas.getSpriteFrames()[this.type];
        this.node.getChildByName("bg").active = !this.clickable();
    }

    //可点击状态
    clickable(): boolean {

        return null;
    }

    //入槽
    toSlot() {

    }


    //出槽
    toSlotCancel() {
        //TOOD

    }


    onLoad() {
        //加载点击事件
        //.on()节点的 事件监听注册方法（Cocos 引擎的 Node 类内置方法），
        // 作用是 “给当前节点绑定一个事件，当事件触发时执行回调”。
        // 语法：node.on(事件类型, 回调函数, 回调函数的 this 指向)

        //回调函数 onTouchStart 内部的 this 指向：这里指定为当前脚本实例，
        // 确保在回调中能通过 this 访问脚本的其他属性 / 方法（比如 this.node、自定义变量等）
        this.node.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    onTouchStart() {
        //TODO
    }

    onTouchEnd() {
        //TODO

    }

    protected onDestroy(): void {
        this.node.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }


}



